package com.yksj.healthtalk.ui.doctor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sfs2x.client.core.SFSEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.yksj.healthtalk.adapter.DoctorAdapter;
import com.yksj.healthtalk.adapter.DoctorAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.adapter.DoctorAdapter.onClickFriendHeadListener;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.RootFragment;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.DoctorParameter;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.friend.DoctorMainActivity;
import com.yksj.healthtalk.ui.setting.PersonalInformationActivity;
import com.yksj.healthtalk.ui.views.DoctorNavigationBar;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.SharePreUtils;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 医生馆
 * 
 * @author Administrator
 * 
 */
public class DoctorMainFragment extends RootFragment implements DoctorNavigationLisenter, OnRefreshListener2<ListView>, OnClickListener,onClickFriendHeadListener, OnItemClickListener,onClickFriendAttentionListener{

	private DoctorNavigationBar mDoctorNavigationBar;
	private PullToRefreshListView mPullToRefreshListView;
	private DoctorAdapter adapter;
	private ArrayList<CustomerInfoEntity> entities;
	private ListView mListView;
	private int size;
	private DoctorParameter parameter;
	String position = "";// pop position
	int clickBtnId = 0;// 导航id
	private CustomerInfoEntity cacheCustomerInfoEntity;
	private AppData mAppData;
	private IntentFilter filter;
	private int isFromDoctor=0;// 1 表示从多美医生来的
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
				LodingFragmentDialog.dismiss(getFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(context, R.string.groupNewFail);
				} else {
					FriendHttpUtil.requestAttentionTofriendsResult(context,cacheCustomerInfoEntity, mAppData);
					adapter.notifyDataSetChanged();
				}
			} else if (action.equals(SFSEvent.CONNECTION_LOST)) {
			} else if (CoreService.ACTION_COMMONT_CONTENT.equals(intent.getAction())){
				DoubleBtnFragmentDialog.showDefault(getChildFragmentManager(),  "亲，您的好评是对我们最大的鼓励~", "下次吧", "鼓励一下",new OnDilaogClickListener() {
					@Override
					public void onDismiss(DialogFragment fragment) {
						SharePreUtils.updateCommentGoodDay();
					}
					@Override
					public void onClick(DialogFragment fragment, View v) {
						SharePreUtils.updateCommentGood();
						SystemUtils.commentGood(getActivity());
					}
				});
			}
		}
	};
	
	private int mDepartmentCode;//科室的code
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		if (isFromDoctor!=1 && getArguments().containsKey("code")) {
			mDepartmentCode = Integer.valueOf(getArguments().getString("code"));
		}
		mAppData = HTalkApplication.getAppData();
		parameter = new DoctorParameter(mDepartmentCode);
		String str = getParameterStr(1, parameter);
		mPullToRefreshListView.setRefreshing();
		if(isFromDoctor==1){
			try {
				JSONObject jsonObject = new JSONObject(str);
				jsonObject.put("DOCTOROFFICE", getArguments().getString("code"));
				jsonObject.put("MAIN_DOCTOR_OFFICE", getArguments().getString("code"));
				str=jsonObject.toString();
				HttpRestClient.doHttpFINDDOCTORSBYASSISTANT(str, new AsyncDoctorListHander(position, clickBtnId));
			} catch (Exception e) {
			}
		}else{
			HttpRestClient.doHttpDoctorMain(str, new AsyncDoctorListHander(position, clickBtnId));	
		}
		
		super.onActivityCreated(savedInstanceState);
	}

	private String getParameterStr(int size, DoctorParameter parameter) {
		if (parameter == null) {
			parameter = new DoctorParameter (mDepartmentCode);
		}
		this.size = size;
		parameter.setCUSTOMERID(SmartFoxClient.getLoginUserId());
		parameter.setPAGESIZE(size);
		return JSON.toJSONString(parameter);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.doctor_main_layout, null);
		initWidget(v);
		initData(v);
		return v;
	}

	private void initWidget(View v) {
		initTitleView(v);
		mDoctorNavigationBar = (DoctorNavigationBar) v
				.findViewById(R.id.doctor_navigationbar);
		mPullToRefreshListView = (PullToRefreshListView) v
				.findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.addFooterView(LayoutInflater.from(getActivity()).inflate(
				R.layout.list_line_layout, null));

		
		
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setBackgroundResource(R.drawable.icon_search_press);

		mDoctorNavigationBar.setDoctorNavigationLisenter(this);
		mPullToRefreshListView.setOnRefreshListener(this);
		titleRightBtn2.setOnClickListener(this);
		titleLeftBtn.setOnClickListener(this);
		mListView.setOnItemClickListener(this);
		String str = getArguments().getString("title");
		if(!TextUtils.isEmpty(str)){
			titleTextV.setText(str+"医生诊所");
		}else{
			titleTextV.setText("医生诊所");
		}
		//从多美医生跳转过来的
		if(1==getArguments().getInt("isDoctor")){
			mDoctorNavigationBar.setHidenView();
			isFromDoctor=1;
			titleTextV.setText(str);
		}
	}

	private void initData(View v) {
		entities = new ArrayList<CustomerInfoEntity>();
		adapter = new DoctorAdapter(getActivity(), entities, false);
		adapter.setonClickFriendHeadListener(this);
		adapter.setonClickFriendAttentionListener(this);
		mListView.setAdapter(adapter);
	}

	@Override
	public void OnSelectService(View v) {
		// TODO Auto-generated method stub
		HttpRestClient.doHttpDoctorSelectService(new AsyncServiceHander(v));
	}

	class AsyncServiceHander extends JsonHttpResponseHandler {
		View v;

		public AsyncServiceHander(View v) {
			super(getActivity());
			this.v = v;
		}

		// [{"SERVICE_TYPE_ID":1,"SERVICE_TYPE":"普通服务"},{"SERVICE_TYPE_ID":2,"SERVICE_TYPE":"预约时段服务"},{"SERVICE_TYPE_ID":3,"SERVICE_TYPE":"预约面访服务"}]
		@Override
		public void onSuccess(int statusCode, JSONObject response) {
			if (response.has("error_message")) {
				try {
					SingleBtnFragmentDialog.showDefault(getChildFragmentManager(),  response.getString("error_message"));
				} catch (JSONException e) {
				}
			}
			super.onSuccess(statusCode, response);
		}

		@Override
		public void onSuccess(int statusCode, JSONArray response) {
			ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
			HashMap<String, String> map = new HashMap<String, String>();
			for (int i = 0; i < response.length(); i++) {
				try {
					map = new HashMap<String, String>();
					JSONObject object = response.getJSONObject(i);
					String service_type_id = "";
					String service_type = "";
					if (object.has("OFFICE_NAME")) {//科室
						 service_type_id = object
								.getString("OFFICE_CODE");
						 service_type = object.getString("OFFICE_NAME");
					}else {//服务类型
						service_type_id = object.getString("SERVICE_TYPE_ID");
						 service_type = object.getString("SERVICE_TYPE");
						 if (list.size() == 0) {
								map.put("SERVICE_TYPE_ID", "0");
								map.put("SERVICE_TYPE", "全部");
								list.add(map);
								map = new HashMap<String, String>();
						}
					}
					map.put("SERVICE_TYPE_ID", service_type_id);
					map.put("SERVICE_TYPE", service_type);
					list.add(map);
					if (v.getId() == 1) {
						mDoctorNavigationBar.choiceService(v, list);
					} else if (v.getId() == 5) {
						mDoctorNavigationBar.choiceDcotorDepartments(v, list);
					}

				} catch (JSONException e) {
				}
				super.onSuccess(statusCode, response);
				}
		}
	}

	// 医生列表请求
	class AsyncDoctorListHander extends ObjectHttpResponseHandler {

		public AsyncDoctorListHander(String position, int clickBtnId) {
			DoctorMainFragment.this.position = position;
			DoctorMainFragment.this.clickBtnId = clickBtnId;
		}

		@Override
		public Object onParseResponse(String content) {
			return JsonParseUtils.jsonfilter(content);
		}

		@Override
		public void onSuccess(int statusCode, Object response) {
			if (size == 1) {
				entities.clear();
			}
			if (response != null && response instanceof ArrayList) {
				++size;
				entities.addAll((Collection<? extends CustomerInfoEntity>) response);
			}else if(response != null && response instanceof String){
				ToastUtil.showShort(getActivity(), response.toString());
			}
			adapter.notifyDataSetChanged();
			super.onSuccess(statusCode, response);
		}

		@Override
		public void onFinish() {
			mPullToRefreshListView.onRefreshComplete();
			super.onFinish();
		}

	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		String parameterStr = getParameterStr(1, parameter);
		if(isFromDoctor==1){
			try {
				JSONObject jsonObject = new JSONObject(parameterStr);
				jsonObject.put("DOCTOROFFICE", getArguments().getString("code"));
				jsonObject.put("MAIN_DOCTOR_OFFICE", getArguments().getString("code"));
				parameterStr=jsonObject.toString();
				HttpRestClient.doHttpFINDDOCTORSBYASSISTANT(parameterStr, new AsyncDoctorListHander(position, clickBtnId));
			} catch (Exception e) {
			}
			
		}else{
			HttpRestClient.doHttpDoctorMain(parameterStr,
					new AsyncDoctorListHander(position, clickBtnId));
		}
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		String parameterStr = getParameterStr(size, parameter);
		if(isFromDoctor==1){
			try {
				JSONObject jsonObject = new JSONObject(parameterStr);
				jsonObject.put("DOCTOROFFICE", getArguments().getString("code"));
				jsonObject.put("MAIN_DOCTOR_OFFICE", getArguments().getString("code"));
				parameterStr=jsonObject.toString();
				HttpRestClient.doHttpFINDDOCTORSBYASSISTANT(parameterStr, new AsyncDoctorListHander(position, clickBtnId));
			} catch (Exception e) {
			}
		}else{
			HttpRestClient.doHttpDoctorMain(parameterStr,new AsyncDoctorListHander(position, clickBtnId));
		}
		
		
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed(v);
			break;
		case R.id.title_right2: //医生精确查找
			Intent intent = new Intent(getActivity(), DoctorExactSearchActivity.class);
			startActivity(intent);
			break;
		}
	}

	@Override
	public void onClickFriendHead(CustomerInfoEntity entity, int positon) {
		if (SmartFoxClient.getLoginUserId().equals(entity.getId())) {
			Intent intent = new Intent();
			intent.setClass(getActivity(), PersonalInformationActivity.class);
			startActivity(intent);
		}else {
			Intent intent = new Intent(getActivity(), DoctorMainActivity.class);
			intent.putExtra("id", entity.getId());
			startActivity(intent);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (0<arg2 && arg2 <= entities.size()) {
			onClickFriendHead(entities.get(arg2-1), arg2-1);
		}
		
	}

	@Override
	public void OnHttpGetDoctorListForNavigation(
			HashMap<Integer, String> allSelect,
			HashMap<Integer, String> hashMap, String position,
			int clickBtnId) { 	
		parameter = new DoctorParameter(mDepartmentCode);
		for (Map.Entry<Integer, String> e : allSelect.entrySet()) {
			switch (e.getKey()) {
			case 1:
				parameter.setSERVICETYPEID(Integer.valueOf(hashMap.get(1)));
				break;
			case 2:
				parameter.setORDERONOFF(Integer.valueOf(hashMap.get(2)));
				break;

			case 3:// 城市
				parameter.setAREA(Integer.valueOf(hashMap.get(3)));
				break;
			case 4:// 医院
				parameter.setDOCTORHOSPITAL(hashMap.get(4));
				break;
			case 5:// 科室
				parameter.setDOCTOROFFICE(Integer.valueOf(hashMap.get(5)));
				parameter.setOFFICEFLAG(1);//科室
				break;
			case 6:// 职称
				parameter.setDOCTORTITLE(Integer.valueOf(hashMap.get(6)));
				break;
			}
		}
		mPullToRefreshListView.setRefreshing();
		HttpRestClient.doHttpDoctorMain(getParameterStr(1, parameter),new AsyncDoctorListHander(position, clickBtnId));
	}

	@Override
	public void onClickFriendAttention(int attentioned,
			CustomerInfoEntity entity, int positon) {
		cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(getActivity(),null, entity);
	}
	
	@Override
	public void onStop() {
		unRegisterReceiver(getActivity());
		super.onStop();
	}
	
	@Override
	public void onStart() {
		registerReceiver(getActivity());
		Intent intent =new Intent(getActivity(),CoreService.class);
		intent.setAction(CoreService.ACTION_FRAME_VIEW_VISIABLE);
		intent.putExtra("className",this.getClass().getName());
		getActivity().startService(intent);

		super.onStart();
	}
	
	
	public void registerReceiver(Context context) {
		filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		filter.addAction(CoreService.ACTION_COMMONT_CONTENT);
		context.registerReceiver(receiver, filter);
	}

	public void unRegisterReceiver(Context context) {
		try {
			context.unregisterReceiver(receiver);
		} catch (Exception e) {
			System.err.println(e);
		}
	}

	//点击科室获取列表信息
	@Override
	public void OnDcotorDepartments(View view) {
		// TODO Auto-generated method stub
		HttpRestClient.doHttpMinDcotorDepartments(null,mDepartmentCode+"",new AsyncServiceHander(view));
	}

}
